﻿using UnityEngine;
using System.Collections;

public class PufferFish : MonoBehaviour {
	public float Force;
	public float acceleration ;
	public static float distanceTraveled;
	private Vector3 startPosition;
	public GameObject targetPosition;
	public static int boosts;
	public GameObject spawnbox;
	float emitTime;
	//public GameObject parentObj;
	Vector3 velocity = new Vector3(6.0f, 0.0f, 0.0f);
	float slowFactor = .5f;  // needs be between 0 and 1
	int clickCounter;
	Vector3 savedTransformScale;
	float startAcceleration;
	public Texture2D[]  pufftextures;
	public Texture2D deathTex;
	// Use this for initialization
	bool death;
	GameObject wtf;
	GameObject wtf2;
	void Start () {
		//Quaternion savedRot =	transform.rotation;
		//transform.rotation = savedRot;
		foreach (Transform child in transform) {
			//	child.renderer.material.mainTexture= pufftextures[Random.Range(0,pufftextures.Length)];
			child.renderer.material.mainTexture= pufftextures[clickCounter];
			child.renderer.enabled = false;
		}
	//	acceleration = 7.5f;
		GameEventManager.GameStart += GameStart;
		GameEventManager.GameOver += GameOver;
		startPosition = transform.localPosition;
		renderer.enabled = false;
		rigidbody.isKinematic = true;
		enabled = false;
		clickCounter = 0;
		startAcceleration = acceleration;
		savedTransformScale  = transform.localScale;
		//Spawner.startSpawning = true;


		}

	private void GameStart () {
		boosts = 0;
		//transform.Rotate(new Vector3(0,0,0));
		transform.rotation = Quaternion.Euler(Vector3.zero);
		GUIManager.SetBoosts(boosts);
		distanceTraveled = 0f;
		GUIManager.SetDistance(distanceTraveled);
		transform.localPosition = startPosition;
		transform.localScale = savedTransformScale;
		renderer.enabled = true;
		rigidbody.isKinematic = false;
		enabled = true;
		Spawner.startSpawning  =true;

		foreach (Transform child in transform) {
			//	child.renderer.material.mainTexture= pufftextures[Random.Range(0,pufftextures.Length)];
			child.renderer.material.mainTexture= pufftextures[clickCounter];
			child.renderer.enabled =true;
		}
		//transform.rotation = Quaternion.Euler(new Vector3( 90, transform.rotation.y,transform.rotation.z));

		}
	private void GameOver () {

		clickCounter = 0;
		foreach (Transform child in transform) {
			//	child.renderer.material.mainTexture= pufftextures[Random.Range(0,pufftextures.Length)];
			child.renderer.material.mainTexture= pufftextures[clickCounter];
			child.renderer.enabled = false;
		}
	//	transform.localPosition = startPosition;


		//rigidbody.isKinematic = true;
		enabled = false;
		Spawner spwnRef = spawnbox.GetComponent<Spawner>();
		spwnRef.deathTime = 0;
		spwnRef.newtime = 0;
		spwnRef.timer = 0;
		GameObject[] sharkRef = GameObject.FindGameObjectsWithTag("shark");

		foreach(GameObject GO in sharkRef){
			Destroy(GO);
		}
		Spawner.startSpawning  =false;
        HighScoreManager.AddHighScore(Mathf.CeilToInt(distanceTraveled));
	}
	void OnTriggerEnter(Collider other){
	if (other.tag == "shark"){

			//Destroy(gameObject);
			foreach (Transform child in transform) {
				//	child.renderer.material.mainTexture= pufftextures[Random.Range(0,pufftextures.Length)];
				child.renderer.material.mainTexture= deathTex;

			}
			death = true;
			wtf2 =Instantiate(Resources.Load("mypart2"),transform.position,transform.rotation) as GameObject;
		//acceleration = 0;
			emitTime = 0;
		}
	}

	void mydeath(){

		Destroy(wtf2,.5f);
		emitTime += Time.deltaTime;
        //Debug.Log(emitTime);

		Spawner.startSpawning = false;
		rigidbody.isKinematic = false;
		if(emitTime > .5f){
			death = false;



		GameEventManager.TriggerGameOver();

		}

	}
	void Update () {
		//DontDestroyOnLoad(transform.gameObject);
		if(death){

			mydeath();
		}
/*
		emitTime += Time.deltaTime;
		Debug.Log(emitTime);
		if(emitTime > 3){
			emitTime = 0;
			Destroy(wtf,3);
		}
*/

		Destroy(wtf,2);

		Vector3 targetPoint =new Vector3(0,0,270);

		Quaternion targetRotation= Quaternion.Euler(new Vector3 (0,0,0));
		if(rigidbody.velocity.y>0 || rigidbody.velocity.y<0 ){
	
			float step = 60* Time.deltaTime;
			transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, step);
		}

		distanceTraveled = transform.localPosition.x;
        if (distanceTraveled >= 0)
        {
            GUIManager.SetDistance(distanceTraveled);
        }
		rigidbody.angularVelocity = Vector3.zero;
		rigidbody.velocity = rigidbody.velocity * (1.0f - (slowFactor * Time.deltaTime));

		if (velocity.magnitude < 0.1f){
			velocity = Vector3.zero;
		}

		if(Mathf.Approximately(slowFactor, 1))
			velocity *= 0;   //Check it the slowfactor is 1 to prevent ln(0) which would throw an exception
		else
			velocity *= (1 + Mathf.Log(1 - slowFactor) * Time.deltaTime);
		rigidbody.AddForce(acceleration, 0f, 0f, ForceMode.Acceleration);

		Rect bounds = new Rect(0,0,Screen.width,Screen.height/2);

		if(Input.GetKeyUp(KeyCode.UpArrow) ){
			acceleration -= .5f;
			foreach (Transform child in transform) {
				child.renderer.material.mainTexture= pufftextures[clickCounter];
			}
			clickCounter ++;
			if(clickCounter <= 4){
				StartCoroutine(LerpScale(.2f));
			}else{
				StartCoroutine(LerpScaleBack(2f));
				clickCounter = 0;
				acceleration = startAcceleration;
				wtf =Instantiate(Resources.Load("mypart"),transform.position,transform.rotation) as GameObject;
				FollowPuffer omg = wtf.GetComponent<FollowPuffer>();
				omg.puffer = gameObject;
			}

			Force = Mathf.Abs(Force);
			rigidbody.velocity = new Vector3(acceleration,Force,acceleration);
			transform.Rotate(new Vector3(0,0,50));


		}
	
		
		if(Input.GetKeyUp(KeyCode.DownArrow)){
			acceleration -= .5f;
			foreach (Transform child in transform) {
				child.renderer.material.mainTexture= pufftextures[clickCounter];
			}
			clickCounter ++;
			if(clickCounter <= 4){
				StartCoroutine(LerpScale(.2f));
			}else{
				StartCoroutine(LerpScaleBack(2f));
				clickCounter = 0;
				acceleration = startAcceleration;
				wtf =Instantiate(Resources.Load("mypart"),transform.position,transform.rotation) as GameObject;
				FollowPuffer omg = wtf.GetComponent<FollowPuffer>();
				omg.puffer = gameObject;
			}
		
			Force = -Mathf.Abs(Force);
			transform.Rotate(new Vector3(0,0,-50));
			rigidbody.velocity = new Vector3(acceleration,Force,acceleration);
			
		}
		if(Input.GetMouseButtonDown(0)){

			acceleration -= .5f;
			foreach (Transform child in transform) {
				child.renderer.material.mainTexture= pufftextures[clickCounter];
			}
			clickCounter ++;
			if(clickCounter <= 4){
				StartCoroutine(LerpScale(.2f));
			}else{
				StartCoroutine(LerpScaleBack(2f));
				clickCounter = 0;
				acceleration = startAcceleration;
				wtf =Instantiate(Resources.Load("mypart"),transform.position,transform.rotation) as GameObject;
				FollowPuffer omg = wtf.GetComponent<FollowPuffer>();
				omg.puffer = gameObject;
			}
			if ( bounds.Contains(Input.mousePosition) ){
				Force = -Mathf.Abs(Force);
				transform.Rotate(new Vector3(0,0,50));
				rigidbody.velocity = new Vector3(acceleration,Force,acceleration);

				}
			if (!bounds.Contains(Input.mousePosition) ){
				Force = Mathf.Abs(Force);
				rigidbody.velocity = new Vector3(acceleration,Force,acceleration);
				transform.Rotate(new Vector3(0,0,-50));
			}
		}
	}
	IEnumerator LerpScale(float time )
	{
		Vector3 originalScale = transform.localScale;
		Vector3 targetScale = originalScale + new Vector3(.1f,.1f, .1f);
		float originalTime = time;
		
		while (time > 0.0f)
		{
			time -= Time.deltaTime;
			
			transform.localScale = Vector3.Lerp(targetScale,originalScale, time / originalTime);
			
			yield return time;
		}
	}
	IEnumerator LerpScaleBack(float time )
	{
		Vector3 originalScale = transform.localScale;
		Vector3 targetScale = savedTransformScale;
		float originalTime = time;
		acceleration = startAcceleration;
		while (time > 0.0f)
		{
			time -= Time.deltaTime;
            //Debug.Log("going back down");
			transform.localScale = Vector3.Lerp(targetScale,originalScale, time / originalTime);
			
			yield return time;
		}
		foreach (Transform child in transform) {
			//	child.renderer.material.mainTexture= pufftextures[Random.Range(0,pufftextures.Length)];
			child.renderer.material.mainTexture= pufftextures[0];
			
			
			
		}

	}
}
